import { createClient } from "redis";
import { logger } from "@/utils/log"; // 日志方法

const client = createClient();
// 设置redis缓存有效期
// client.expire("token", 7200); //2h自动过期

// 配置redis的监听事件
// 准备连接redis-server事件
client.on("ready", () => {
  logger.log("Redis client: ready");
});

// 连接到redis-server事件
client.on("connect", () => {
  logger.log("Redis is connected！");
});

// 重连redis
client.on("reconnecting", () => {
  logger.log("Redis reconnecting");
});

// redis关闭
client.on("end", () => {
  logger.log("Redis Closed！");
});

// redis警告
client.on("warning", () => {
  logger.log("Redis client warning");
});

// reids错误
client.on("error", (error) => {
  logger.error({ message: "Redis Error", error });
});

// 连接redis
client.connect();

// redis存储数据
export type SetKeyValue = (
  key: string,
  value: any
) => Promise<string | Error | void>;
export const setKeyValue: SetKeyValue = async (key, value) => {
  if (!value) {
    logger.error({ message: "redis value 不能为空" });
    return;
  }
  if (typeof value == "object") {
    value = JSON.stringify(value);
  }
  try {
    const res = await client.set(key, value);
    logger.log(`redis set ${res}`);
  } catch (error) {
    logger.error({ message: "Redis set 失败", error });
  }
};

// redis获取数据
export const getKeyValue = async (key: string) => {
  const data = await client.get(key);
  return JSON.parse(data);
};
